package com.application.model;

import com.jfinal.ext.kit.MsgException;
import com.platform.annotation.Table;
import com.platform.mvc.base.BaseModel;

import java.util.List;
import java.util.Map;

@SuppressWarnings("unused")
@Table(tableName = Area.table_name, pkName = "id")
public class Area extends BaseModel<Area> {

    private int id;
    private String name;

    public static final Integer ROOT_ID = 0;

    public int getId() {
        return get("id");
    }

    public String getName() {
        return get("name", "");
    }

    public static final Area dao = new Area();

    public static final String table_name = "t_area";

    public Area findParent(Integer id) {
        return findFirst("select * from t_area where id = (select parent_id from t_area where id = ?)", id);
    }

    public Area findDetail(String id) {
        return findFirst("select a.*,b.name as parentName from t_area a " +
                " left join t_area b on a.parent_id = b.id " +
                " where a.id = ? order by a.ord", id);
    }

    public List<?> findList(int level, Integer pid) {
//        if(pid == null){
//            pid = 510000;//默认显示四川
//        }
        String sql = "select * from "+ table_name +" where level = ? and status = 1 ";
        if(pid != null) {
            sql += " and parent_id = " + pid;
        }
        sql += " order by ord";
        return find(sql, level);
    }

    public Area create(Map<String, String> map) {
        String pid = map.get("parent_id");

        Area obj = new Area();
        obj.set("parent_id", pid);
        obj.set("name", map.get("name"));
        obj.set("ord", map.get("ord"));
        obj.set("status", map.get("status"));

         /*
        设置path
         */
        if(pid == null || ROOT_ID.equals(pid)){
            obj.set("level", 1);
            obj.set("path", ROOT_ID);
        } else {
            Area p = Area.dao.findById(pid);
            if(p == null){
                throw new MsgException("上级区域设置错误");
            }
            obj.set("level",  (p.getInt("level") + 1));
            obj.set("path", p.get("path") + "/" + pid);
        }

        return obj;
    }

    public Area findByName(String s1, String s2, String s3) {
        String s = "select * from " + table_name + " where (name = ? or name = ? or name = ?) ";
//        Area a1 = findFirst(s, s1, s1, s1+"省");
//        if(a1 != null){
        Area a2 = findFirst(s, s2, s2, s2+"市");
        if(a2 != null){
            Area a3 = findFirst(s + "and parent_id = ?", s3, s3+"区", s3+"县", a2.getId());
            if(a3 != null){
                return a3;
            }
        }
//        }
        return null;
    }

    public List<Area> query(String key) {
        String s = "select a.*,b.name as parent_name from t_area a left join t_area b on a.parent_id = b.id " +
                "where instr(a.name, ?) > 0 and a.level =3 order by a.name limit 10";
        return find(s, key);
    }
}
